import { Divider } from 'antd'
import { QRCodeSVG } from 'qrcode.react'
import { useEffect, useState } from 'react'

import { getTradeOrderByTradeIdApi, payCompanionOrderApi } from '@/api/pcs/pcsCompanionOrder'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { formatDate } from '@/utils/displayHelper'
import EnumManager, { PCS_COMPANION_PERIOD_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

import CashSel from './imgs/cash-sel.png'
import Cash from './imgs/cash.png'
import WeixinSel from './imgs/weixin-sel.png'
import Weixin from './imgs/weixin.png'
import wx from './imgs/wx.png'
import styles from './index.module.less'

const PAYMENT_TYPE_ENUM = new EnumManager({
  WECHAT: { value: 'wechat', label: '微信支付', img: Weixin, imgSel: WeixinSel },
  OFFLINE: { value: 'cash', label: '线下支付', img: Cash, imgSel: CashSel },
})

const PayModal = ({
  tradeId,
  fileUrl,
  startDate,
  startPeriod,
  endDate,
  endPeriod,
  payableAmount,
  day,
  qrcodeUrl,
  onSubmit,
}) => {
  const [sel, setSel] = useState(PAYMENT_TYPE_ENUM.WECHAT)
  const [countdown, setCountdown] = useState(60)

  const onOk = async () => {
    await requestWithTry(payCompanionOrderApi, { tradeId, payWay: PAYMENT_TYPE_ENUM.OFFLINE })
    return true
  }

  const checkTradeOrder = () => {
    const interval = setInterval(async () => {
      const { data } = await requestWithTry(getTradeOrderByTradeIdApi, { tradeId })
      if (data.status !== 'paid') return
      onSubmit(true)
    }, 2000)
    return interval
  }

  useEffect(() => {
    let countdown = 60
    const countdownInterval = setInterval(async () => {
      countdown -= 1
      if (countdown === 0) {
        onSubmit(false)
        return
      }
      setCountdown(countdown)
    }, 1000)
    const interval = checkTradeOrder()
    return () => {
      clearInterval(countdownInterval)
      clearInterval(interval)
    }
  }, [])

  return (
    <AekModal
      title='支付'
      width={600}
      onOk={onOk}
      okText='付款完成'
      cancelButtonProps={{
        style: { display: 'none' },
      }}
      okButtonProps={{
        style: sel === PAYMENT_TYPE_ENUM.WECHAT ? { display: 'none' } : {},
      }}
    >
      <div>{countdown}s后将自动关闭当前弹窗</div>
      <div className={styles.tip}>待支付金额</div>
      <div className={styles.amount}>
        ￥<span className='text-36px'>{payableAmount}</span>
      </div>
      <div className={styles.days}>
        服务天数：{day}天({formatDate(startDate)} {PCS_COMPANION_PERIOD_ENUM.getText(startPeriod)} ~{' '}
        {formatDate(endDate) || ''} {PCS_COMPANION_PERIOD_ENUM.getText(endPeriod) || ''})
      </div>
      <Divider size='small' />
      <div className='text-14px'>支付方式：</div>
      <div className='flex'>
        {PAYMENT_TYPE_ENUM.options.map(({ value, label, img, imgSel }) => (
          <div
            key={value}
            className={`${styles.btnPayType} ${sel === value ? styles.btnPayTypeSel : ''}`}
            onClick={() => setSel(value)}
          >
            <img src={sel === value ? imgSel : img} alt='' />
            <span className='ml8px'>{label}</span>
          </div>
        ))}
      </div>
      {sel === PAYMENT_TYPE_ENUM.WECHAT && (
        <div className={styles.codeContent}>
          <div className={styles.QRCode}>
            <QRCodeSVG value={qrcodeUrl} style={{ height: 116, width: 116 }} />
            <div className='flex items-center justify-center'>
              <img src={wx} width={17} />
              <span className='ml8px'>微信支付</span>
            </div>
          </div>
          <div className={styles.comp}>杭州昀和科技服务产业有限公司</div>
        </div>
      )}
      {sel === PAYMENT_TYPE_ENUM.OFFLINE && fileUrl && (
        <div className={styles.codeContent}>
          <img src={fileUrl} alt='' style={{ height: 116, width: 116 }} />
        </div>
      )}
    </AekModal>
  )
}

PayModal.PromiseThen = PromiseThen

export default PayModal
